import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from '@/store'
import { message } from 'antd'

type ColorStateType = {
  value: string
  status: 'idle' | 'loading' | 'succeeded' | 'failed'
}

const initialState: ColorStateType = {
  value: '#000',
  status: 'idle'
}

// 请大家注意：调用 createAsyncThunk() 函数之后，它的返回值，是一个 Thunk creator 函数
// 如果我们想得到真正的 Thunk 函数，还需要再次调用 getColorThunkCreator() 才行
// createAsyncThunk 的第一个参数，是 action-type 的前缀
export const getColorThunkCreator = createAsyncThunk('color/getcolor', async () => {
  // 在这个函数中，可以执行异步操作
  try {
    const controller = new AbortController()
    setTimeout(() => controller.abort(), 3000)
    const response = await fetch('https://api.liulongbin.top/v1/color', { signal: controller.signal })
    const res = await response.json()
    console.log(res)
    return res.data
  } catch (err) {
    return Promise.reject(err)
  }
})

const colorSlice = createSlice({
  name: 'color',
  initialState,
  reducers: {},
  extraReducers(builder) {
    builder
      .addCase(getColorThunkCreator.pending, (state) => {
        console.log('正在请求中...')
        state.status = 'loading'
      })
      .addCase(getColorThunkCreator.fulfilled, (state, action: PayloadAction<{ color: string }>) => {
        console.log('请求成功了...', action)
        state.value = action.payload.color
        state.status = 'succeeded'
      })
      .addCase(getColorThunkCreator.rejected, (state, action) => {
        console.log(action.error)
        // 1. 关闭 loading
        state.status = 'failed'
        // 2. 把背景色变成红色
        state.value = 'red'
        // 3. 使用 antd 提供的 message 组件提示一个错误消息
        // message.error('请求失败，请稍后再试！')
        message.error(action.error.message)
      })
  }
})

export default colorSlice.reducer

// selectors
export const selectColor = (state: RootState) => state.color.value
export const selectColorLoading = (state: RootState) => state.color.status === 'loading'
